<?php
//2010-01-12 11:09AM EST
require_once('jsonrpc2.class.php');

class transport_http extends jsonrpc2{
    public $key = 'jsonrpc';
    
    public function parse(){
        $error = -32603;
        try{
            $r = $this->resolve_from_single_parameterized_call();
            if($r===FALSE) $r = $this->resolve_from_blob();
            if(is_object($r) || is_array($r)) return json_encode($this->dispatch_batch($r));
            throw new Exception(-32600);                
        }
        catch(Exception $e){
            $error = $e->getMessage();
        }
        return json_encode((object) array('error'=> (object) array('code'=>$error, 'message'=>$this->errors[$error])));
    }

    private function resolve_from_single_parameterized_call(){
        if(isset($_REQUEST['method'])){
            $r = (object) array('method'=>null,'params'=>array(),'id'=>null,'jsonrpc'=>'1.0');
            foreach($r as $k=>$v){
                if(isset($_REQUEST[$k])){
                    $i=json_decode($_REQUEST[$k],TRUE);
                    $r->$k = ( $i ) ? $i : $_REQUEST[$k];
                }
            }
        }        
        return isset($r) ? $r : FALSE;
    }
    
    private function resolve_from_blob(){
        $b = isset($_REQUEST[$this->key]) ? json_decode($_REQUEST[$this->key], TRUE) : null;
        if(!is_array($b)) $b = json_decode(rawurldecode($_SERVER['QUERY_STRING']), TRUE);
        if(!is_array($b)) $b = json_decode(file_get_contents('php://input'), TRUE);        
        if(!is_array($b)) throw new Exception(-32700);        
        if(!isset($b[0])) return$this-> map_into($b); //non-batch
        foreach($b as &$item) $item = $this->map_into($item);
        return $b;
    }
    
    private function map_into($i){
        $r = array('method'=>null,'params'=>array(),'id'=>null,'jsonrpc'=>'1.0');
        foreach($r as $k=>$v){
            if(isset($i[$k])) $r[$k] = $i[$k];    
        }
        return (object) $r;
    }
}